﻿Imports System.IO
Imports System.Data.SqlClient
Imports Gif.Components

Public Class TELA_START
    Public emulador As Process
    Public BANCO As New InnerLibs.Databases.SQL(My.Settings.Conexao)
    Public iniciogameplay As DateTime
    Public segundos As Integer = 7
    Public makegif As Boolean = False
    Public GIFARRAY As New List(Of Image)
    Public gifname As String

    Sub redimensionaricones()

        For Each controle As RibbonTab In Ribbon1.Tabs
            For Each novo As RibbonPanel In controle.Panels
                For Each item In novo.GetItems
                    Try
                        item.Image = item.Image.ResizeImage(30, 30)
                    Catch ex As Exception

                    End Try

                Next
            Next
        Next


        For Each controle In Ribbon1.OrbDropDown.MenuItems
            Try
                controle.Image = controle.Image.ResizeImage(30, 30)
                controle.ToolTipImage = My.Resources.Question_Coin.ResizeImage(50, 50)
            Catch ex As Exception
                'faz nada
            End Try

        Next
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles cronometro.Tick
        Try
            recScreen.Start()
            If File.Exists(CurDir() & "\DATA\IMG\" & listadejogos.SelectedItems(0).Text & ".jpg") = False And emulador.ProcessName = "zsnesw" Then
                If segundos > 0 Then
                    icone.ShowBalloonTip(200, "CAPTURANDO TELA DE TITULO", "Por favor, aguarde " & segundos & " segundos para começar a jogar." & vbNewLine & "Estamos reconhecendo a tela inicial da ROM", ToolTipIcon.Warning)
                    segundos = segundos - 1
                Else
                    If segundos = 0 Then
                        AppActivate(emulador.Id)
                        SendKeys.Send("%" + "{PRTSC}")
                        Dim Screenshot As Image = Clipboard.GetImage()
                        Screenshot.Save(CreateAndReturn("\DATA\IMG\") & listadejogos.SelectedItems(0).Text & ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
                        icone.ShowBalloonTip(200, "TELA CRIADA", "Obrigado por aguardar. Você já pode começar a jogar!", ToolTipIcon.Info)
                    End If
                End If
            End If
        Catch ex As Exception
        End Try
        Try
            Dim programa As String = emulador.ProcessName
            If emulador.HasExited Then
                ' infobox.Focus()
                segundos = 7
                Me.Show()
                cronometro.Stop()
                recScreen.Stop()
                listararquivos()
                If programa = "zsnesw" Then
                    Dim ler As System.IO.StreamReader
                    Dim tempogameplay = emulador.ExitTime - emulador.StartTime
                    If File.Exists(CurDir() & "\data\rominfo.txt") Then
                        ler = IO.File.OpenText(CurDir() & "\data\rominfo.txt")
                        'infobox.Clear()
                        ' infobox.AppendText(ler.ReadToEnd().Replace("This is the info for the last game you ran.", "Informações da ultima hack jogada:" & vbNewLine & vbNewLine & "Inicio do Gameplay:   " & iniciogameplay.ToString & vbNewLine & "Final do Gameplay:   " & Date.Now.ToString))
                        If tempogameplay.Hours > DateAndTime.Minute("01:00:00") Then
                            'infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Hours & " horas " & tempogameplay.Minutes & "minutos")
                        Else
                            If tempogameplay.Minutes > DateAndTime.Minute("00:01:00") Then
                                'infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Minutes & " minutos")
                            Else
                                'infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Seconds & " segundos (só?) ")
                            End If
                        End If
                    End If
                    If makegif = True Then
                        'fazgif
                        Dim gif As New AnimatedGifEncoder
                        Dim filedialog As New SaveFileDialog
                        filedialog.FileName = gifname
                        filedialog.Filter = "Animações GIF|*.gif"
                        If filedialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                            gif.Start(filedialog.FileName)
                            Dim cont As Integer = 1

                            For Each ImagemX As Image In GIFARRAY
                                gif.AddFrame(ImagemX)
                                icone.ShowBalloonTip(5000, "CRIANDO GAMEPLAY EM GIF", "Exportando quadro " & cont, ToolTipIcon.Info)
                                cont = cont + 1
                            Next
                            gif.SetRepeat(0)
                            gif.Finish()
                            makegif = False
                            GIFARRAY.Clear()
                        End If
                    End If
                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
            cronometro.Stop()
            Exit Sub
        End Try
    End Sub


    Private Sub TELA_START_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        redimensionaricones()
        PegaGrupo()
        listadejogos.Dock = DockStyle.Fill
        LISTASERVIDOR.Dock = DockStyle.Fill
        listararquivos()
        My.Resources.zsnesw.WriteToFile(CreateAndReturn("DATA"), "zsnesw.exe")

        Ribbon1.OrbText = Environment.UserName.ToUpper & "| Modo Offline"




    End Sub
    Sub listarhacksservidor()

        LISTASERVIDOR.Groups.Clear()
        Dim cats As SqlDataReader = BANCO.ExecuteSQL("SELECT * FROM HACKCATEGORIA WHERE CAT_ATIVO = 1")
        While cats.Read
            LISTASERVIDOR.Groups.Add(New ListViewGroup(cats("CAT_NOME").ToString, cats("CAT_NOME").ToString))
        End While
        cats.Close()

        Dim cogumelim As Integer
        Dim STATUS As String
        Dim listagem As SqlDataReader = BANCO.ExecuteSQL("EXEC ListarHacksAtivas")
        While listagem.Read
            Dim arq As String = CreateAndReturn("DATA\ROMS\" & listagem("CAT_NOME")) & "\" & listagem("HACK_NOME") & ".smc"
            If File.Exists(arq) = True Then
                Dim arquivo As New FileInfo(arq)
                If arquivo.CreationTime < Convert.ToDateTime(listagem("HACK_DH_UPLOAD")) Then
                    cogumelim = 1
                    STATUS = "DESATUALIZADO"
                Else
                    cogumelim = 0
                    STATUS = "BAIXADO"
                End If
            Else
                cogumelim = 6
                STATUS = "NÃO BAIXADO"
            End If

            LISTASERVIDOR.Items.Add(listagem("HACK_NOME"), cogumelim).Group = LISTASERVIDOR.Groups.Item(listagem("CAT_NOME").ToString)
            LISTASERVIDOR.Items(LISTASERVIDOR.Items.Count - 1).SubItems.Add(listagem("HACK_AUTOR").ToString)
            LISTASERVIDOR.Items(LISTASERVIDOR.Items.Count - 1).SubItems.Add(Convert.ToDateTime(listagem("HACK_DH_UPLOAD").ToString()).ToShortDateString)
            LISTASERVIDOR.Items(LISTASERVIDOR.Items.Count - 1).SubItems.Add(listagem("HACK_DOWNLOADS").ToString)
            LISTASERVIDOR.Items(LISTASERVIDOR.Items.Count - 1).SubItems.Add(listagem("HACK_ID").ToString)
            LISTASERVIDOR.Items(LISTASERVIDOR.Items.Count - 1).SubItems.Add(STATUS)
            LISTASERVIDOR.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            LISTASERVIDOR.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
        End While
    End Sub
    Sub PegaGrupo()
        listadejogos.Groups.Clear()
        filtro_categoria.DropDownItems.Clear()
        Dim itemT As New RibbonLabel
        itemT.Text = "TODAS"
        filtro_categoria.DropDownItems.Add(itemT)
        For Each diretorio As DirectoryInfo In New DirectoryInfo(CreateAndReturn("\DATA\ROMS\")).GetDirectories
            listadejogos.Groups.Add(New ListViewGroup(diretorio.Name, diretorio.Name.ToUpper()))
            Dim item As New RibbonLabel
            item.Text = diretorio.Name
            filtro_categoria.DropDownItems.Add(item)
        Next



    End Sub

    Function gerarcogumelo(arquivo As FileInfo) As Integer
        Dim cogumelo As Integer
        Select Case arquivo.Directory.Name
            Case "HACK"
                cogumelo = 5
            Case "ROM ORIGINAL"
                cogumelo = 0
            Case "KAIZO HACK"
                cogumelo = 3
            Case "IMPORTADO"
                cogumelo = 1
            Case Else
                cogumelo = 6
        End Select
        Return cogumelo

    End Function
    Sub listararquivos(Optional nomearquivo As String = "*", Optional categoria As String = "")
        PegaGrupo()
        If categoria = "TODAS" Then categoria = ""
        Try
            listadejogos.Items.Clear()
            Dim diretorio As New DirectoryInfo(CurDir() & "\DATA\ROMS\" & categoria)
            Dim arquivos As FileInfo() = diretorio.GetFiles("*" & nomearquivo & "*.smc", SearchOption.AllDirectories)
            For Each arquivo As FileInfo In arquivos
                listadejogos.Items.Add(New ListViewItem(arquivo.Name, gerarcogumelo(arquivo))).Group = listadejogos.Groups.Item(arquivo.Directory.Name)
                listadejogos.Items(listadejogos.Items.Count - 1).SubItems.Add((Math.Round(arquivo.Length / 1024)).ToString() & " KB")
                listadejogos.Items(listadejogos.Items.Count - 1).SubItems.Add(arquivo.CreationTime.ToString)
            Next
            RibbonTab1.Text = "Suas Hacks - Total: " & listadejogos.Items.Count.ToString
            listadejogos.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            listadejogos.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
        Catch ex As Exception
        End Try

    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click

        Dim sp As New SHOW_PROPS(CurDir() & "\DATA\ROMS\" & listadejogos.SelectedItems(0).Group.Name & "\" & listadejogos.SelectedItems(0).Text, CType(Me.Handle, IntPtr))
    End Sub

    Private Sub loadrom_Click(sender As Object, e As EventArgs) Handles loadrom.Click
        Try
            Clipboard.Clear()
            jogalast.Text = "Jogar " & listadejogos.SelectedItems.Item(0).Text
            Me.Hide()

            emulador = Process.Start(CurDir() & "\data\zsnesw.exe", "-m """ & CurDir() & "\DATA\ROMS\" & listadejogos.SelectedItems.Item(0).Group.Name & "\" & listadejogos.SelectedItems.Item(0).Text & """")
            iniciogameplay = Now
            cronometro.Start()

            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "Emulando " & listadejogos.SelectedItems.Item(0).Text
            icone.ShowBalloonTip(600)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
            listararquivos()
        End Try
    End Sub

    Private Sub LISTASERVIDOR_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles downloadit.Click, LISTASERVIDOR.MouseDoubleClick
        baixarhack(LISTASERVIDOR.SelectedItems(0).SubItems(4).Text)
    End Sub

    Sub baixarhack(id As Integer)
        Try
            Dim baixahack = BANCO.ExecuteSQL("SELECT HACK_DH_UPLOAD, HACK_NOME, HACK_ARQUIVO, (SELECT CAT_NOME FROM HackCategoria where CAT_ID = HACK.CAT_ID) as HACK_CATEGORIA FROM HACK WHERE HACK_ID = " & id)
            baixahack.Read()
            Dim caminho As String = "\DATA\ROMS\" & baixahack("HACK_CATEGORIA")
            caminho = CreateAndReturn(caminho)
            Dim arq = caminho & "\" & baixahack("HACK_NOME") & ".smc"
            If File.Exists(arq) Then
                Dim arquivo As New FileInfo(arq)
                If arquivo.CreationTime < Convert.ToDateTime(baixahack("HACK_DH_UPLOAD")) Then
                    baixahack("HACK_ARQUIVO").WriteToFile(caminho, baixahack("HACK_NOME") & ".smc")
                    arquivo.CreationTime = Convert.ToDateTime(baixahack("HACK_DH_UPLOAD"))
                    BANCO.ExecuteSQL("UPDATE HACK SET HACK_DOWNLOADS = HACK_DOWNLOADS + 1 where hack_id = convert(int," & LISTASERVIDOR.SelectedItems(0).SubItems(4).Text & ")")
                Else
                    MsgBox("Sua Hack já está atualizada!", MsgBoxStyle.Information)
                End If
            Else
                Dim file As Byte() = baixahack("HACK_ARQUIVO")
                file.WriteToFile(caminho, baixahack("HACK_NOME") & ".smc")
                Dim arquivo As New FileInfo(arq)
                arquivo.CreationTime = Convert.ToDateTime(baixahack("HACK_DH_UPLOAD"))
                BANCO.ExecuteSQL("UPDATE HACK SET HACK_DOWNLOADS = HACK_DOWNLOADS + 1 where hack_id = convert(int," & LISTASERVIDOR.SelectedItems(0).SubItems(4).Text & ")")
            End If
            search.TextBoxText = baixahack("HACK_NOME")
            listadejogos.BringToFront()

        Catch ex As Exception
            MsgBox("Erro ao baixar a ROM." & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub RibbonButton2_Click(sender As Object, e As EventArgs) Handles RibbonOrbOptionButton3.Click
        My.Settings.NomeUsuario = ""
        My.Settings.LoginUsuario = ""
        My.Settings.EmailUsuario = ""
        My.Settings.IdUsuario = 0
        My.Settings.SenhaUsuario = ""
        My.Settings.idPerfil = 0
        My.Settings.PerfilUsuario = ""
        My.Settings.Save()
        Application.Restart()
    End Sub

    Private Sub RibbonOrbMenuItem4_Click(sender As Object, e As EventArgs) Handles publish.Click
        TELA_EDITARHACK.Show()
    End Sub


    Private Sub search_TextBoxKeyDown(sender As Object, e As EventArgs) Handles search.TextBoxTextChanged
        listararquivos(nomearquivo:=search.TextBoxText)
    End Sub

    Private Sub filtro_categoria_TextBoxTextChanged(sender As Object, e As EventArgs) Handles filtro_categoria.TextBoxTextChanged
        listararquivos(categoria:=filtro_categoria.TextBoxText)
    End Sub

    Private Sub RibbonTab2_ActiveChanged(sender As Object, e As EventArgs) Handles RibbonTab2.ActiveChanged
        LISTASERVIDOR.BringToFront()
    End Sub

    Private Sub RibbonTab1_ActiveChanged(sender As Object, e As EventArgs) Handles RibbonTab1.ActiveChanged
        listadejogos.BringToFront()
    End Sub

    Private Sub RibbonButton1_Click(sender As Object, e As EventArgs) Handles RibbonButton1.Click

        listarhacksservidor()
        RibbonButton1.Text = "Atualizar Lista"
        RibbonButton1.Image = My.Resources._1UP_Mushroom.ResizeImage(30, 30)
        RibbonTab2.Text = "Servidor - Total: " & LISTASERVIDOR.Items.Count
    End Sub

    Private Sub listadejogos_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles listadejogos.MouseDoubleClick
        loadrom.PerformClick()
    End Sub


    Private Sub listadejogos_MouseClick(sender As Object, e As MouseEventArgs) Handles listadejogos.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then menurom.Show(MousePosition)
    End Sub

    Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
        makegif = True
        gifname = listadejogos.SelectedItems(0).Text & ".gif"
        loadrom.PerformClick()
    End Sub

    Private Sub recscreen_Tick(sender As Object, e As EventArgs) Handles recScreen.Tick
        ' Dim ScreenSize As New Size(Emutamanho("zsnesw", "ZSNES"))
        Dim ScreenSize = My.Computer.Screen.WorkingArea.Size
        Dim BMP As New Bitmap(ScreenSize.Width, ScreenSize.Height)
        Dim g As System.Drawing.Graphics = Graphics.FromImage(BMP)
        g.CopyFromScreen(New Point(0, 0), New Point(0, 0), ScreenSize)
        GIFARRAY.Add(BMP)
    End Sub

    Structure RECT
        Public Left As Integer
        Public Top As Integer
        Public Right As Integer
        Public Bottom As Integer
    End Structure

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
    Private Declare Function GetWindowRect Lib "user32" Alias "GetWindowRect" (ByVal hwnd As Integer, ByVal lpRect As RECT) As Integer


    Function Emutamanho(nomeprocesso As String, nomejanela As String) As Size
        Dim emurect As RECT
        Dim emulador_ela As Integer
        emulador_ela = FindWindow(nomeprocesso, nomejanela)
        GetWindowRect(emulador_ela, emurect)
        MsgBox("Top = " & emurect.Top & _
            vbCrLf & "Bottom = " & emurect.Bottom & _
            vbCrLf & "Left = " & emurect.Left & _
            vbCrLf & "Right = " & emurect.Right)
        Return New Size()
    End Function
End Class